const express = require('express');
const mysql = require('mysql');
const { resolve } = require('path');
const { db } = require('../conf/index');
const pool = mysql.createPool(db);

module.exports = {
    query: function(sql, params = [], once = false) {

        return new Promise((resolve, reject) => {
            pool.getConnection((err, con) => {
                if (err) {
                    console.error('数据库连接失败',err);
                    reject(Error('database connect fail'))
                } else {
                    con.query(sql, params, (err, result) => {
                        if (err) {
                            throw Error(err);
                        }
                        if (once) {
                            resolve(result[0] || []);
                        } else {
                            resolve(result);
                        }
                        con.release();
                    })
                }
            })
        })
    }
}